/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.user;

import java.io.*;

import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
import model.*;
import model.fbUser.LoginValidation;
import model.pojo.UserProfile;

/**
 *
 * @author Yasith
 */
public class login extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        LoginValidation result = fbUser.ValidateLogin(request.getParameter("email"), request.getParameter("password"));
        
        if (result == LoginValidation.Succesful) {
            fbSession fbs = new fbSession();
            fbs.setLoggedInTime(new Date());
            fbs.setUser(fbUser.getUser(request.getParameter("email")));
            
            UserProfile up = fbUserProfile.getUserProfile(fbs.getUser().getUserID());
            fbs.setUserProfile(up);
            
            request.getSession().setAttribute("fbSession", fbs);
            
            request.setAttribute("message", "Logged in Succesfully!");
            request.setAttribute("returnToURL", "index.jsp");

        } else if (result == LoginValidation.InvalidEmail) {
            request.setAttribute("message", "Sorry Authentication Failed, a user account with that email address doesn't exsit.");
            request.setAttribute("returnToURL", "login.jsp");

        } else if (result == LoginValidation.WrongPassword) {
            request.setAttribute("message", "Sorry Authentication Failed, wrong password");
            request.setAttribute("returnToURL", "login.jsp");
        }

        request.getRequestDispatcher("message.jsp").forward(request, response);

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
